﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Outlook.WorkItems.Extension.Controls
{
    public class IconsCache
    {
        public static int GetIconIndex(ImageList imageList, string extension)
        {
            if (!imageList.Images.ContainsKey(extension))
            {
                Icon icon = NativeMethods.GetIconForFile(extension, true);
                imageList.Images.Add(extension, icon);

            }
            return imageList.Images.IndexOfKey(extension);
        }
    }

    internal static class NativeMethods
    {
        [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr SHGetFileInfoW(string pszPath, int dwFileAttributes, ref ShFileInfoW psfi, int cbSizeFileInfo, int uFlags);

        public static Icon GetIconForFile(string fileExtension, bool small)
        {
            ShFileInfoW psfi = new ShFileInfoW();
            int uFlags = 0x110;
            if (small)
            {
                uFlags |= 1;
            }
            else
            {
                uFlags = uFlags;
            }
            SHGetFileInfoW(fileExtension, 0, ref psfi, Marshal.SizeOf(psfi), uFlags);
            return Icon.FromHandle(psfi.hIcon);
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal struct ShFileInfoW
        {
            public IntPtr hIcon;
            public int iIcon;
            public int dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        }
    }

}
